<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片检测</title>
    <style>
        #drop-area {
            border: 2px dashed #ccc;
            border-radius: 20px;
            width: 80%;
            margin: 20px auto;
            padding: 20px;
            text-align: center;
            font-family: sans-serif;
        }

        #drop-area.highlight {
            border-color: purple;
        }

        #file-input {
            display: none;
        }

        #preview-container {
            margin: 20px auto;
            text-align: center;
            position: relative;
        }

        #preview-image {
            max-width: 80%;
            display: none;
        }

        #detect-btn {
            background-color: #4CAF50;
            border: none;
            color: white;
            padding: 15px 32px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin: 20px 2px;
            cursor: pointer;
            border-radius: 8px;
            display: none;
            position: absolute;
            top: 10px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 10;
        }

        #detect-btn:hover {
            background-color: #45a049;
        }

        .detection-box {
            position: absolute;
            border: 2px solid #ff0000;
            pointer-events: none;
        }
        
        #url-input-area {
            width: 80%;
            margin: 20px auto;
            text-align: center;
            padding: 20px;
            border: 2px dashed #ccc;
            border-radius: 20px;
        }
        
        #image-url {
            width: 70%;
            padding: 10px;
            font-size: 16px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        
        #load-url-btn {
            background-color: #008CBA;
            border: none;
            color: white;
            padding: 10px 20px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin: 10px 2px;
            cursor: pointer;
            border-radius: 8px;
        }
        
        #load-url-btn:hover {
            background-color: #007B9A;
        }
    </style>
</head>

<body>
    <h1 style="text-align: center;">图片检测系统</h1>

    <div id="drop-area">
        <p>拖拽图片到此处或点击选择图片</p>
        <input type="file" id="file-input" accept="image/*">
        <button onclick="document.getElementById('file-input').click()">选择图片</button>
        <p style="font-size: 14px; color: #666;">提示：也可以直接粘贴图片 (Ctrl+V)</p>
    </div>

    <!-- 添加图片链接输入区域 -->
    <div id="url-input-area">
        <p>或者输入图片链接</p>
        <input type="text" id="image-url" placeholder="粘贴图片链接 here...">
        <button id="load-url-btn">加载图片</button>
    </div>

    <div id="preview-container">
        <button id="detect-btn">检测</button>
        <img id="preview-image" alt="预览图片">
    </div>

    <script>
        let uploadedFile = null;

        const dropArea = document.getElementById('drop-area');
        const fileInput = document.getElementById('file-input');
        const previewImage = document.getElementById('preview-image');
        const detectBtn = document.getElementById('detect-btn');
        const previewContainer = document.getElementById('preview-container');
        // 添加URL相关元素
        const imageUrlInput = document.getElementById('image-url');
        const loadUrlBtn = document.getElementById('load-url-btn');

        // 添加对粘贴事件的监听
        document.addEventListener('paste', handlePaste);

        // 防止默认拖拽行为
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, preventDefaults, false);
            document.body.addEventListener(eventName, preventDefaults, false);
        });

        // 添加高亮效果
        ['dragenter', 'dragover'].forEach(eventName => {
            dropArea.addEventListener(eventName, highlight, false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, unhighlight, false);
        });

        // 处理文件拖拽
        dropArea.addEventListener('drop', handleDrop, false);
        fileInput.addEventListener('change', handleFiles, false);

        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }

        function highlight() {
            dropArea.classList.add('highlight');
        }

        function unhighlight() {
            dropArea.classList.remove('highlight');
        }

        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            handleFiles({ target: { files: files } });
        }

        function handleFiles(e) {
            const files = e.target.files;
            if (files.length > 0) {
                uploadedFile = files[0];
                const reader = new FileReader();
                reader.onload = function (event) {
                    previewImage.src = event.target.result;
                    previewImage.style.display = 'block';
                    detectBtn.style.display = 'inline-block';
                    // 清除之前的检测框
                    clearDetectionBoxes();
                };
                reader.readAsDataURL(uploadedFile);
            }
        }

        // 处理粘贴事件
        function handlePaste(e) {
            const items = (e.clipboardData || e.originalEvent.clipboardData).items;
            for (let item of items) {
                if (item.type.indexOf('image') !== -1) {
                    const blob = item.getAsFile();
                    const reader = new FileReader();
                    reader.onload = function (event) {
                        previewImage.src = event.target.result;
                        previewImage.style.display = 'block';
                        detectBtn.style.display = 'inline-block';
                        // 清除之前的检测框
                        clearDetectionBoxes();
                        
                        // 重置文件上传状态
                        uploadedFile = blob;
                    };
                    reader.readAsDataURL(blob);
                    break;
                }
            }
        }

        function clearDetectionBoxes() {
            // 移除所有检测框
            const boxes = document.querySelectorAll('.detection-box');
            boxes.forEach(box => box.remove());
        }

        function drawDetectionBoxes(boxes) {
            console.log('Detection boxes:', boxes)
            // 清除之前的检测框
            clearDetectionBoxes();

            // 获取图片尺寸
            const imgRect = previewImage.getBoundingClientRect();
            const imgWidth = previewImage.naturalWidth;
            const imgHeight = previewImage.naturalHeight;

            // 绘制每个检测框
            boxes.forEach(box => {
                // 修改：适配新的数据结构
                const { x1, y1, x2, y2, confidence, class_id, class_name } = box;

                // 计算相对于显示图片的坐标和尺寸
                const left = (x1 / imgWidth) * imgRect.width;
                const top = (y1 / imgHeight) * imgRect.height;
                const width = ((x2 - x1) / imgWidth) * imgRect.width;
                const height = ((y2 - y1) / imgHeight) * imgRect.height;

                // 创建检测框元素
                const boxElement = document.createElement('div');
                boxElement.className = 'detection-box';
                boxElement.style.left = `${left}px`;
                boxElement.style.top = `${top}px`;
                boxElement.style.width = `${width}px`;
                boxElement.style.height = `${height}px`;
                boxElement.title = `${class_name} (${confidence.toFixed(2)})`;

                // 添加标签
                const label = document.createElement('div');
                label.style.position = 'absolute';
                label.style.top = '-20px';
                label.style.left = '0px';
                label.style.background = 'rgba(255, 0, 0, 0.8)';
                label.style.color = 'white';
                label.style.padding = '2px 6px';
                label.style.fontSize = '12px';
                label.style.fontFamily = 'Arial, sans-serif';
                label.style.borderRadius = '3px';
                label.style.whiteSpace = 'nowrap';
                label.style.boxShadow = '0 1px 3px rgba(0,0,0,0.3)';
                label.textContent = `${class_name} ${confidence.toFixed(2)}`;

                boxElement.appendChild(label);
                previewContainer.appendChild(boxElement);
            });
        }

        detectBtn.addEventListener('click', detectImage);

        // 添加URL加载功能
        loadUrlBtn.addEventListener('click', loadImageUrl);
        imageUrlInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                loadImageUrl();
            }
        });

        function loadImageUrl() {
            const url = imageUrlInput.value.trim();
            if (!url) {
                alert('请输入图片链接');
                return;
            }

            // 验证是否为图片链接
            if (!isValidImageUrl(url)) {
                alert('请输入有效的图片链接');
                return;
            }

            // 加载图片
            previewImage.src = url;
            previewImage.style.display = 'block';
            detectBtn.style.display = 'inline-block';
            // 清除之前的检测框
            clearDetectionBoxes();
            
            // 重置文件上传状态
            uploadedFile = null;
        }

        function isValidImageUrl(url) {
            // 简单验证URL格式
            try {
                new URL(url);
                // 检查是否为图片扩展名
                const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'];
                return imageExtensions.some(ext => url.toLowerCase().includes(ext));
            } catch (e) {
                return false;
            }
        }

        // 修改detectImage函数以支持URL图片
        async function detectImage() {
            if (!uploadedFile && !previewImage.src) return;

            try {
                detectBtn.disabled = true;
                detectBtn.textContent = '检测中...';

                let response;
                if (uploadedFile) {
                    // 文件上传检测
                    const formData = new FormData();
                    formData.append('image', uploadedFile);
                    
                    response = await fetch('/detectimg', {
                        method: 'POST',
                        body: formData
                    });
                } else {
                    // URL图片检测
                    const requestData = {
                        image_url: previewImage.src
                    };
                    
                    response = await fetch('/detectimg_url', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(requestData)
                    });
                }

                if (response.ok) {
                    const data = await response.json();
                    console.log('Detection boxes:', data.boxes.boxes)
                    // 显示原图作为结果图

                        // 绘制检测框
                        if (data.boxes.boxes && data.boxes.boxes.length > 0) {

                            drawDetectionBoxes(data.boxes.boxes);
                        }
                } else {
                    alert('检测失败');
                }
            } catch (error) {
                console.error('Error:', error);
                alert('检测出错');
            } finally {
                detectBtn.disabled = false;
                detectBtn.textContent = '检测';
            }
        }
    </script>
</body>

</html>